package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class BlockingQueueExampleService {

    private final BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);

    // 生产者方法，模拟消息生产
    public void produce(String message) throws InterruptedException {
        log.info("尝试生产消息: {}", message);
        boolean added = queue.offer(message, 2, TimeUnit.SECONDS); // 使用 offer 方法，等待最多2秒
        if (added) {
            log.info("成功生产消息: {}", message);
        } else {
            log.warn("队列已满，无法生产消息: {}", message);
        }
    }

    // 消费者方法，模拟消息消费
    public void consume() throws InterruptedException {
        log.info("等待消费消息...");
        String message = queue.poll(2, TimeUnit.SECONDS); // 使用 poll 方法，等待最多2秒
        if (message != null) {
            log.info("成功消费消息: {}", message);
        } else {
            log.warn("没有可消费的消息");
        }
    }

    // 检查队列中的剩余容量
    public int getRemainingCapacity() {
        int remainingCapacity = queue.remainingCapacity();
        log.info("队列剩余容量: {}", remainingCapacity);
        return remainingCapacity;
    }
}
